package com.rongxun.utils.wallet;

import com.rongxun.base.IBase;
import com.rongxun.hbwallet.constants.ErrorCode;
import com.rongxun.utils.FlyLog;

import io.reactivex.subscribers.ResourceSubscriber;

public abstract class WalletSubscriber<T> extends ResourceSubscriber<T> {
    private final String FATAL_EOR = "500";  //返回数据失败,严重的错误

    private IBase.IView mView;

    public abstract void onSuccess(T t);

    public WalletSubscriber(IBase.IView pView) {
        mView = pView;
    }

    @Override
    public void onStart() {
        super.onStart();
        mView.showLoading(true);
    }

    /**
     * 简单的把Dialog 处理掉
     */
    @Override
    public void onComplete() {
        mView.showLoading(false);
        FlyLog.d("onComplete");
    }


    @Override
    public void onNext(T response) {

        if (response == null) {
            onFailure(ErrorCode.WALLET_NULL, "钱包为空");
        } else {
            onSuccess(response);
        }
    }

    @Override
    public final void onError(Throwable t) {
        mView.showLoading(false);
        String errorCode = "-1111";
        String errorMsg = "未知的错误！";

        if (t instanceof RuntimeException) {
            errorCode = FATAL_EOR;
            errorMsg = "运行时错误";
        }
        FlyLog.e("errorCode" + errorCode + "errorMsg" + errorMsg);
        onFailure(errorCode, errorMsg);
    }




    /**
     * Default error dispose!
     * 一般的就是 AlertDialog 或 SnackBar
     *
     * @param code
     * @param message
     */
    private void onFailure(String code, String message) {
        disposeEorCode(message, code);
        mView.showError(message, code);
    }

    /**
     * 对通用问题的统一拦截处理
     *
     * @param code
     */
    public abstract void disposeEorCode(String message, String code);


}
